<template>
  <view class="content">
    <!-- 页面头部区域，包含搜索框和店铺信息展示 -->
    <view class="header">
      <!-- 搜索框，用户可在此输入商品名称进行搜索 -->
      <view class="search">
        <input
          type="text"
          placeholder="请输入商品名称"
          style="padding-left: 40px"
        />
      </view>
      <!-- 循环展示店铺信息，每个店铺信息包含图片、名称、月售、起送条件、基础运费和标语 -->
      <view class="listcontent" v-for="shop in shops" :key="shop.id">
        <view class="listitem">
          <img :src="shop.imgUrl" width="80px" height="80px" />
        </view>
        <view class="listitem listcon">
          {{ shop.name }}
          <view class="listrow">
            <view>月售：{{ shop.sales }}</view>
            <view>起送：{{ shop.expressLimit }}</view>
            <view>基础运费：{{ shop.expressPrice }}</view>
          </view>
          <view style="color: red">{{ shop.slogan }}</view>
        </view>
      </view>
    </view>
    <!-- 中间商品分类和商品列表区域 -->
    <view class="middleshops">
      <!-- 商品分类切换按钮区域 -->
      <view class="click">
        <!-- 全部商品按钮，点击可切换到全部商品列表，通过动态类名控制按钮样式 -->
        <view
          class="item"
          :class="{ active: index === 1 }"
          @click="switchView(1)"
        >全部商品</view>
        <!-- 秒杀按钮，点击可切换到秒杀商品列表，通过动态类名控制按钮样式 -->
        <view
          class="item"
          :class="{ active: index === 2 }"
          @click="switchView(2)"
        >秒杀</view>
        <!-- 新鲜水果按钮，点击可切换到新鲜水果商品列表，通过动态类名控制按钮样式 -->
        <view
          class="item"
          :class="{ active: index === 3 }"
          @click="switchView(3)"
        >新鲜水果</view>
      </view>
      <!-- 商品列表展示区域，根据不同的分类标志（flag）展示对应的商品列表 -->
      <view class="message">
        <!-- 当flag为1时，展示全部商品列表 -->
        <view v-if="flag === 1" class="i">
          <view class="shop">
            <!-- 循环展示每个商品信息，包括图片、名称、月售、价格、原价和加入购物车按钮 -->
            <view class="itemlist" v-for="p in products" :key="p.id">
              <view class="con">
                <img :src="p.imgUrl" alt="" width="70px" height="70px" />
              </view>
              <view class="con">
                <view class="title">{{ p.name }}</view>
                <view>月售 {{ p.sales }}</view>
                <view class="row">
                  <view class="price">￥{{ p.price }}</view>
                  <view class="oldPrice">￥{{ p.oldPrice }}</view>
                </view>
              </view>
              <view class="con button">
                <!-- 加入购物车按钮，点击调用buttonhaddcart方法将商品加入购物车 -->
                <view @click="buttonhaddcart(p)">
                  <button>加入购物车</button>
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 当flag为2时，展示秒杀商品列表 -->
        <view v-if="flag === 2" class="i">
          <view class="shop">
            <view class="itemlist" v-for="p in products" :key="p.id">
              <view class="con">
                <img :src="p.imgUrl" alt="" width="70px" height="70px" />
              </view>
              <view class="con">
                <view class="title">{{ p.name }}</view>
                <view>月售 {{ p.sales }}</view>
                <view class="row">
                  <view class="price">￥{{ p.price }}</view>
                  <view class="oldPrice">￥{{ p.oldPrice }}</view>
                </view>
              </view>
              <view class="con button">
                <view @click="buttonhaddcart(p)">
                  <button>加入购物车</button>
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 当flag为3时，展示新鲜水果商品列表 -->
        <view v-if="flag === 3" class="i">
          <view class="shop">
            <view class="itemlist" v-for="p in products" :key="p.id">
              <view class="con">
                <img :src="p.imgUrl" alt="" width="70px" height="70px" />
              </view>
              <view class="con">
                <view class="title">{{ p.name }}</view>
                <view>月售 {{ p.sales }}</view>
                <view class="row">
                  <view class="price">￥{{ p.price }}</view>
                  <view class="oldPrice">￥{{ p.oldPrice }}</view>
                </view>
              </view>
              <view class="con button">
                <view @click="buttonhaddcart(p)">
                  <button>加入购物车</button>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="cart-icon" @click="toggleCart">
      <uni-icons type="cart"></uni-icons>
      <view class="cart-badge" v-if="totalQuantity > 0">{{ totalQuantity }}</view>
    </view>

    <!-- 购物车面板 -->
    <view class="cart-panel" :class="{ show: showCart }">
      <view class="cart-header">
        <view class="cart-title">购物车</view>
        <view class="clear-cart" @click="clearCurrentSupermarketCart">清空购物车</view>
      </view>

      <view class="cart-items">
        <view class="cart-item" v-for="(item, index) in filteredCartList" :key="index">
          <view class="item-select" @click="toggleItemSelect(item)">
            <uni-icons :type="item.selected ? 'checkbox-filled' : 'circle'" color="#1aad19"></uni-icons>
          </view>
          <view class="item-image">
            <img :src="item.imgUrl" width="60" height="60" />
          </view>
          <view class="item-info">
            <view class="item-name">{{ item.name }}</view>
            <view class="item-price">¥{{ item.price }}</view>
          </view>
          <view class="item-quantity">
            <view class="quantity-btn" @click="decreaseQuantity(item)">-</view>
            <view class="quantity-number">{{ item.quantity }}</view>
            <view class="quantity-btn" @click="increaseQuantity(item)">+</view>
          </view>
        </view>
      </view>

      <view class="cart-footer">
        <view class="select-all" @click="toggleSelectAll">
          <uni-icons :type="isAllSelected ? 'checkbox-filled' : 'circle'" color="#1aad19"></uni-icons>
          <text>全选</text>
        </view>
        <view class="total-price">
          合计: <text class="price">¥{{ totalPrice }}</text>
        </view>
        <view class="checkout-btn" @click="checkout">去结算({{ selectedCount }})</view>
      </view>
    </view>

    <!-- 遮罩层 -->
    <view class="overlay" v-if="showCart" @click="toggleCart"></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopid: "",
      shops: [],
      products: [],
      flag: 1,
      index: 1,
      cartlist: [], // 购物车数据
      showCart: false, // 控制购物车信息是否显示
    };
  },

  computed: {
    // 过滤出本超市的购物车商品
    filteredCartList() {
      return this.cartlist.filter(item => item.shopId === this.shopid);
    },
    // 选中的商品
    selectedItems() {
      return this.filteredCartList.filter(item => item.selected);
    },
    // 选中商品的总数量
    selectedCount() {
      return this.selectedItems.reduce((sum, item) => sum + item.quantity, 0);
    },
    // 购物车中所有商品的总数量
    totalQuantity() {
      return this.filteredCartList.reduce((sum, item) => sum + item.quantity, 0);
    },
    // 选中商品的总价格
    totalPrice() {
      return this.selectedItems.reduce((sum, item) => sum + (item.price * item.quantity), 0).toFixed(2);
    },
    // 是否全选
    isAllSelected() {
      return this.filteredCartList.length > 0 &&
        this.filteredCartList.every(item => item.selected);
    }
  },
  onLoad(options) {
    const id2 = options.id;
    this.shopid = options.id;
    this.shopsdata(id2);
    this.switchView(1);

    // 初始化时加载购物车数据
    this.loadCartData();
  },
  methods: {
    // 加载购物车数据
    loadCartData() {
      const userId = uni.getStorageSync('userId');
      uni.request({
        url: `http://localhost:3000/users/${userId}`,
        success: (res) => {
          if (res.data && res.data.cart) {
            this.cartlist = res.data.cart;
          }
        },
        fail: (err) => {
          console.error('加载购物车数据失败', err);
        }
      });
    },
    // 保存购物车数据到接口
    saveCartData() {
      const userId = uni.getStorageSync('userId');
      uni.request({
        url: `http://localhost:3000/users/${userId}`,
        method: 'PATCH',
        data: {
          cart: this.cartlist
        },
        success: () => {
          console.log('购物车数据保存成功');
        },
        fail: (err) => {
          console.error('保存购物车数据失败', err);
        }
      });
    },
    shopsdata(id2) {
      console.log(id2);
      uni.request({
        url: `http://localhost:3000/hotList?_id=${id2}`,
        success: (res) => {
          this.shops = res.data;
        },
      });
    },
    switchView(index) {
      if (this.flag === 1) {
        this.flag = index;
        this.index = index;
        uni.request({
          url: `http://localhost:3000/products?shopid=${this.shopid}`,
          success: (res) => {
            this.products = res.data.map(product => ({
              ...product,
              id: product._id // 将后端返回的_id映射到id字段
            }));
          }
        });
      } else if (this.flag === 2) {
        this.flag = index;
        this.index = index;
        uni.request({
          url: `http://localhost:3000/seck?shopid=${this.shopid}`,
          success: (res) => {
            this.products = res.data;
          },
        });
      } else if (this.flag === 3) {
        this.flag = index;
        this.index = index;
        uni.request({
          url: `http://localhost:3000/fruit?shopid=${this.shopid}`,
          success: (res) => {
            this.products = res.data;
          },
        });
      }
    },
    // 切换购物车显示/隐藏
    toggleCart() {
      this.showCart = !this.showCart;
    },
    // 加入购物车方法
    buttonhaddcart(product) {
      // 检查商品是否已经在购物车中
      const existingItem = this.cartlist.find(
        item => item.id === product.id && item.shopId === this.shopid
      );

      if (existingItem) {
        existingItem.quantity++;
        uni.showToast({
          title: '商品数量已增加',
          icon: 'success'
        });
      } else {
        // 将商品添加到购物车
        const newItem = {
          id: product.id,
          name: product.name,
          price: product.price,
          oldPrice: product.oldPrice,
          imgUrl: product.imgUrl,
          sales: product.sales,
          quantity: 1,
          shopId: this.shopid,
          shopName: this.shops[0]?.name || "未知超市",
          selected: true, // 默认选中
        };

        this.cartlist.push(newItem);
        uni.showToast({
          title: '已加入购物车',
          icon: 'success'
        });
      }

      this.saveCartData();
    },
    // 切换单个商品的选择状态
    toggleItemSelect(item) {
      item.selected = !item.selected;
      this.saveCartData();
    },
    // 全选/取消全选
    toggleSelectAll() {
      const shouldSelectAll = !this.isAllSelected;
      this.filteredCartList.forEach(item => {
        item.selected = shouldSelectAll;
      });
      this.saveCartData();
    },
    // 增加商品数量
    increaseQuantity(item) {
      item.quantity++;
      this.saveCartData();
    },
    // 减少商品数量
    decreaseQuantity(item) {
      if (item.quantity > 1) {
        item.quantity--;
        this.saveCartData();
      } else {
        // 如果数量为1，再次减少则从购物车移除
        this.removeFromCart(item);
      }
    },
    // 从购物车移除商品
    removeFromCart(item) {
      const index = this.cartlist.findIndex(
        cartItem => cartItem.id === item.id && cartItem.shopId === item.shopId
      );
      if (index !== -1) {
        this.cartlist.splice(index, 1);
        this.saveCartData();
        uni.showToast({
          title: '已移除商品',
          icon: 'success'
        });

        // 如果购物车为空，自动关闭购物车面板
        if (this.filteredCartList.length === 0) {
          this.showCart = false;
        }
      }
    },
    // 清空当前超市购物车
    clearCurrentSupermarketCart() {
      this.cartlist = this.cartlist.filter(item => item.shopId !== this.shopid);
      this.saveCartData();
      uni.showToast({
        title: '购物车已清空',
        icon: 'success'
      });
    },
    // 结算
    checkout() {
      if (this.selectedCount === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }

      // 这里可以添加结算逻辑，比如跳转到订单确认页面
      uni.showToast({
        title: `结算 ${this.selectedCount} 件商品，总价 ¥${this.totalPrice}`,
        icon: 'none'
      });
      uni.switchTab({
        url: '/pages/cart/index'
      });
    }
  }
};
</script>

<style scoped>
.content .header .listcontent {
  margin-top: 20px;
  width: 100%;
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid grey;
  margin-left: 20px;
  padding-bottom: 20px;
}
.content .header .listcontent .listitem .listrow {
  display: flex;
  flex-direction: row;
  padding-top: 10px;
  padding-bottom: 10px;
}
.content .header .listcontent .listitem .listrow view {
  margin-right: 20px;
}
.content .header .listcontent .listcon {
  margin-left: 30px;
  font-size: 25px;
}
.content .header .search input {
  border: 1px solid aliceblue;
  border-radius: 2ch;
  width: 50%;
  height: 40px;
  background-color: aliceblue;
  margin-top: 15px;
  margin-left: 10px;
}
/* 中间 */
.content .middleshops {
  display: flex;
}
.content .middleshops .click {
  width: 20%;
  background-color: rgb(245, 248, 248);
}
.content .middleshops .click .item {
  width: 100%;
  height: 40px;
  text-align: center;
  margin-top: 20px;
}
.content .middleshops .click .item.active {
  background-color: pink;
}
.content .middleshops .message {
  width: 80%;
}
.message .itemlist {
  display: flex;
  margin-left: 20px;
}
.message .i {
  margin-bottom: 20px;
}
.message .shop {
  margin-top: 10px;
  width: 100%;
}
.message .shop .itemlist {
  margin-bottom: 20px;
}
.itemlist .con {
  margin-right: 40px;
}
.itemlist .button {
  display: flex;
  align-items: center;
  margin-right: 20px;
}
.itemlist .button button {
  margin-right: 10px;
  margin-left: 10px;
  border-radius: 5pt;
  margin: 0 auto;
  color: #f0f0f0;
  background-color: #1aad19;
}
.itemlist .con .title {
  margin-bottom: 10px;
  font-weight: bolder;
  font-size: 24px;
}
.itemlist .con .row {
  margin-top: 10px;
  display: flex;
}
.itemlist .con .row .price {
  color: red;
}
.itemlist .con .row .oldPrice {
  color: grey;
  padding-left: 20px;
  text-decoration: line-through;
}

/* 购物车图标样式 */
.cart-icon {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 50px;
  height: 50px;
  background-color: #1aad19;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  z-index: 999;
}

.cart-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: red;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 购物车面板样式 */
.cart-panel {
  position: fixed;
  bottom: -100%;
  left: 0;
  right: 0;
  height: 60vh;
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1001;
  transition: bottom 0.3s ease;
}

.cart-panel.show {
  bottom: 0;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.cart-title {
  font-size: 18px;
  font-weight: bold;
}

.clear-cart {
  font-size: 14px;
  color: #666;
}

.cart-items {
  height: calc(60vh - 150px);
  overflow-y: auto;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.item-select {
  margin-right: 10px;
}

.item-image {
  margin-right: 10px;
}

.item-image img {
  border-radius: 5px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.item-price {
  font-size: 16px;
  color: #f40;
  font-weight: bold;
}

.item-quantity {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 25px;
  height: 25px;
  line-height: 25px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 50%;
  font-size: 16px;
}

.quantity-number {
  margin: 0 10px;
  min-width: 20px;
  text-align: center;
}

.cart-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.select-all {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.select-all text {
  margin-left: 5px;
}

.total-price {
  font-size: 14px;
  margin-left: 20px;
}

.price {
  color: #f40;
  font-weight: bold;
  font-size: 16px;
}

.checkout-btn {
  background-color: #1aad19;
  color: #fff;
  padding: 8px 15px;
  border-radius: 20px;
  font-size: 14px;
}

/* 遮罩层样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}
</style>    